/*******************************************************************************
 * Copyright (c) 2012, 2013 XML-Print Project.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     XML-Print Project - initial API and implementation
 ******************************************************************************/
package info.xmlprint.ui.editor;

import info.xmlprint.action.CmdToPDF;
import info.xmlprint.core.mapping.MappingGroup;
import info.xmlprint.run.Configuration;
import info.xmlprint.run.WorkbenchInfo;
import info.xmlprint.run.XML2Foplus;
import info.xmlprint.ui.message.GuiMessages; 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;

public class EditorOutputWriter {
	private Logger logger = Logger.getLogger(this.getClass().getName());
	/*
	public void Write2XMLP() {
		String importFilePath = StileditorManager.getImportFilePath();
		if (importFilePath != null) {
			saveToZip(importFilePath);
		} else {
			write2NewXMLP();
		}
	}

	public void write2Xml() {
		openDialog("xml");
	}

	public void write2PDF() {
		openDialog("pdf");
	}

	private void writePDF(String filePath) {

		String editorText = WorkbenchInfo.getActiveEditorText();
		if (editorText != null) {
			// fo erzeugen
			XML2Foplus pdfOut = new XML2Foplus(editorText);
			pdfOut.setXslSour(StileditorManager.getMappingGroup().getXslDoc());
			// fo to pdf transformieren
			CmdToPDF ctp = new CmdToPDF();
			ctp.setPDFPath(filePath);
			if (!ctp.isStop() && pdfOut.getResultFoFile() != null) {
				ctp.transform();
				MessageDialog.openInformation(null, null, filePath + " "
						+ GuiMessages.General_Gui_Save_Success + ".");
			}
		}
	}

	public void write2NewXMLP() {
		FileDialog dialog = new FileDialog(Display.getCurrent()
				.getActiveShell(), SWT.SAVE);
		dialog.setFilterNames(new String[] { ".xmlp" });
		dialog.setFilterExtensions(new String[] { "*.xmlp", "*.*" });

		String fileName = dialog.open();
		if (fileName != null) {
			File tmp = new File(fileName);
			if (tmp.exists()) {
				if (MessageDialog
						.openConfirm(
								null,
								"",
								"Es befindet sich bereits eine Datei desselben Names an diesem Ort, die vorhandene Datei ersetzen?")) {
					saveToZip(fileName);
				}
			} else {
				saveToZip(fileName);
			}
		}
	}

	private void saveToZip(String filePath) {
		FileOutputStream f = null;
		File tempFile = new File(Configuration.getInstance()
				.getXmlprintTmpDir() + new Date().getTime() + ".TMP");
		try {
			f = new FileOutputStream(tempFile);
			CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
			ZipOutputStream zos = new ZipOutputStream(csum);
			BufferedOutputStream out = new BufferedOutputStream(zos);

			OutputFormat of = new OutputFormat();
			of.setIndent(true);
			of.setNewlines(true);
			Writer writer = new OutputStreamWriter(out, "UTF-8");
			XMLWriter xmlWriter = new XMLWriter(writer, of);

			// doc
			String editorText = WorkbenchInfo.getActiveEditorText();
			String xmlFileName = WorkbenchInfo.getActiveEditor().getTitle();
			int idx = xmlFileName.lastIndexOf(":");
			if (idx > -1 && xmlFileName.length() > idx + 1) {
				xmlFileName = xmlFileName.substring(idx + 1);
				xmlFileName = xmlFileName.trim();
			}

			if (editorText != null) {
				InputStream is = new BufferedInputStream(
						new ByteArrayInputStream(editorText.getBytes("utf-8")));
				addToZip("Content\\" + xmlFileName, zos, out, is);
			}

			// MappingGroup
			MappingGroup mg = StileditorManager.getMappingGroup();
			if (mg.getXmlDoc() != null) {
				addToZip("Mapping\\mappings.xml", zos, xmlWriter,
						mg.getXmlDoc());
			}

			// format
			if (mg.getFormatGroup().getXmlDoc() != null)
				addToZip("Format\\formats.xml", zos, xmlWriter, mg
						.getFormatGroup().getXmlDoc());

			// Fo + XSL
			if (editorText != null && mg.getXslDoc() != null) {
				XML2Foplus pdfOut = new XML2Foplus(editorText);
				Document xsl = mg.getXslDoc();
				addToZip("XSLT\\templates.xslt", zos, xmlWriter, xsl);

				pdfOut.setXslSour(xsl);

				String foFilePath = pdfOut.getResultFoFile();
				if (foFilePath != null) {
					InputStream is = new BufferedInputStream(
							new FileInputStream(foFilePath));
					addToZip("FO\\output.fo", zos, out, is);
				}
			}

			xmlWriter.close();
			out.close();
			File newOutputFile = new File(filePath);
			FileModify.deleteFile(newOutputFile);
			FileModify.copyFile(tempFile, newOutputFile);
			StileditorManager.setImportFilePath(filePath);
			FileModify.deleteFile(tempFile);
			MessageDialog.openInformation(null, null, filePath + " "
					+ GuiMessages.General_Gui_Save_Success + ".");

		} catch (FileNotFoundException e) {
			MessageDialog.openError(null, null, "Error in Save" + filePath);
			logger.error("", e);
			e.printStackTrace();
		} catch (IOException e) {
			MessageDialog.openError(null, null, "Error in Save" + filePath);
			logger.error("", e);
			e.printStackTrace();
		}
	}

	private void openDialog(String fileType) {
		if (WorkbenchInfo.getActiveEditorText() == null)
			return;

		FileDialog dialog = new FileDialog(Display.getCurrent()
				.getActiveShell(), SWT.SAVE);
		dialog.setFilterNames(new String[] { "." + fileType });
		dialog.setFilterExtensions(new String[] { "*." + fileType });

		String fileName = dialog.open();
		if (fileName != null) {
			if (fileType.equalsIgnoreCase("xml")) {
				writeXml(fileName);
			} else if (fileType.equalsIgnoreCase("pdf")) {
				writePDF(fileName);
			}
		}
	}

	private void writeXml(String fileName) {
		try {
			Document doc = DocumentHelper.parseText(WorkbenchInfo
					.getActiveEditorText());
			OutputFormat of = new OutputFormat();
			of.setIndent(true);
			of.setNewlines(true);
			Writer writer = new OutputStreamWriter(new FileOutputStream(
					fileName), "UTF-8");

			XMLWriter xmlWriter = new XMLWriter(writer, of);
			xmlWriter.write(doc);
			xmlWriter.close();
			writer.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void addToZip(String zipFileEntry, ZipOutputStream zos,
			BufferedOutputStream out, InputStream in) throws IOException {

		ZipEntry zp = new ZipEntry(zipFileEntry);
		zos.putNextEntry(zp);

		if (in == null) {
			return;
		}

		int c;
		while ((c = in.read()) != -1) {
			out.write(c);
		}
		in.close();

		out.flush();

	}

	private void addToZip(String zipFileEntry, ZipOutputStream zos,
			XMLWriter xmlWriter, Document doc) {

		ZipEntry zp = new ZipEntry(zipFileEntry);
		try {
			zos.putNextEntry(zp);
		} catch (IOException e) {
			logger.error("", e);
			e.printStackTrace();
		}
		if (doc == null)
			return;

		try {
			xmlWriter.write(doc);
			xmlWriter.flush();
		} catch (IOException e) {
			logger.error("", e);
			e.printStackTrace();
		}

	}*/
}
